package com.kingdee.pda.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

//import com.kingdee.commonlib.entity.MyAppInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 扫描本地安装的应用,工具类
 *
 * @author ZhuHuaHua
 * @date 2018/5/14 16:09
 */


public class ApkTool {
    private static final String TAG = ApkTool.class.getSimpleName();
    public static final String KEY_WANG = "com.wangpos.by.cashier3";    //旺POS收银
    /**
     * 扫描所有已经安装的应用
     *
     * @param packageManager
     * @return
     */
    public static List<MyAppInfo> scanLocalInstallAppList(PackageManager packageManager) {
        List<MyAppInfo> myAppInfoList = new ArrayList<>();
        try {
            List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packageInfoList.size(); i++) {
                PackageInfo packageInfo = packageInfoList.get(i);
                //过滤掉系统app
                if ((ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) != 0) {
                    continue;
                }
                MyAppInfo myAppInfo = new MyAppInfo();
                myAppInfo.setAppName(packageInfo.packageName);
                if (packageInfo.applicationInfo.loadIcon(packageManager) == null) {
                    continue;
                }
                myAppInfo.setImage(packageInfo.applicationInfo.loadIcon(packageManager));
                myAppInfoList.add(myAppInfo);
            }
        } catch (Exception e) {
            Log.e(TAG, "===============获取应用包信息失败");
        }
        return myAppInfoList;
    }

    /**
     * 查找应用是否安装
     *
     * @param packageManager
     * @param queryPackage
     * @return
     */
    public static boolean isInstallApk(PackageManager packageManager, String queryPackage) {
        try {
            List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packageInfoList.size(); i++) {
                PackageInfo packageInfo = packageInfoList.get(i);
                if (packageInfo.packageName.equals(queryPackage)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "===============获取应用包信息失败");
        }
        return true;
    }


    public static void installApk(Context context, String apkPath) {
        if (context == null || TextUtils.isEmpty(apkPath)) {
            return;
        }


        File file = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.v(TAG,"7.0以上，正在安装apk...");
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, CommonUtil.getPackageName(context), file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            Log.v(TAG,"7.0以下，正在安装apk...");
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        context.startActivity(intent);


//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        //判断是否是AndroidN以及更高的版本
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            Uri contentUri = FileProvider.getUriForFile(UniportalLoginActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", new File(localFile));
//            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//        } else {
//            intent.setDataAndType(Uri.fromFile(new File(localFile)), "application/vnd.android.package-archive");
//        }
//        UniportalLoginActivity.this.startActivity(intent);
    }

    public static void wangPosCheckUpdate(Context context, String url) {

        Log.d(TAG, "wangPosCheckUpdate:  before");
        Intent intent = new Intent("android.intent.action.APK_INSTALL");//设置action
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);//设置Flags
        intent.putExtra("filePath", url);//设置文件路径
        context.sendBroadcast(intent);//发送广播
        ToastUtils.showShort(context, "发送广播");
    }

    /**
     * 获取当前apk的版本号
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}
